package com.atguigu.day11;

import com.atguigu.bean.Acc;
import com.atguigu.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

public class FlinkSQL18_Function_UDAF {

    public static void main(String[] args) throws Exception {

        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //2.读取端口数据并转换为JavaBean
        SingleOutputStreamOperator<WaterSensor> waterSensorDS = env.socketTextStream("hadoop102", 9999)
                .map(line -> {
                    String[] fields = line.split(",");
                    return new WaterSensor(fields[0],
                            Long.parseLong(fields[1]),
                            Double.parseDouble(fields[2]));
                });

        //3.将流转换为动态表
        Table table = tableEnv.fromDataStream(waterSensorDS);

        //4.使用UDTF
        //4.1 TableAPI：不注册使用
        Table select1 = table.groupBy($("id"))
                .select($("id"), call(MyAvg.class, $("vc")));

        //4.2 TableAPI：注册使用
        tableEnv.createTemporarySystemFunction("myAvg", MyAvg.class);
        Table select2 = table.groupBy($("id"))
                .select($("id"), call("myAvg", $("vc")));

        //4.3 SQL：注册使用
        Table select3 = tableEnv.sqlQuery("select id,myAvg(vc) from " + table + " group by id");

        //5.转换为流进行打印
        tableEnv.toRetractStream(select1, Row.class).print("TableAPI:不注册使用>>>>>>>>>");
        tableEnv.toRetractStream(select2, Row.class).print("TableAPI:注册使用>>>>>>>>>>>");
        tableEnv.toRetractStream(select3, Row.class).print("SQL:注册使用>>>>>>>>>>>>>>>>");

        //6.启动
        env.execute();
    }

    public static class MyAvg extends AggregateFunction<Double, Acc> {

        @Override
        public Acc createAccumulator() {
            return new Acc(0.0D, 0);
        }

        public void accumulate(Acc accumulator, Double value) {
            accumulator.setVcSum(accumulator.getVcSum() + value);
            accumulator.setCount(accumulator.getCount() + 1);
        }

        @Override
        public Double getValue(Acc accumulator) {
            return accumulator.getVcSum() / accumulator.getCount();
        }

    }
}
